package artid.com.arttogo.activity;

import android.graphics.Bitmap;
import android.media.Image;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import java.util.ArrayList;

import artid.com.arttogo.R;
import artid.com.arttogo.fragment.CollecterDynActivity;
import artid.com.arttogo.fragment.CollecterIntroActivity;
import artid.com.arttogo.fragment.CollecterNewsActivity;
import artid.com.arttogo.fragment.CollecterOnsaleActivity;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.utils.VeDate;

public class CollecterActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener {
	/** 导航栏 */
	private HorizontalScrollView mHorizontalScrollView;
	/** 导航条目 */
	private LinearLayout mLinearLayout;
	/** 导航底部线条 */
	private ImageView mImageView;
	/** 页面展示ViewPager */
	private ViewPager pager;
	/** 屏幕宽度 */
	private int mScreenWidth;
	/** 导航条目宽度 */
	private int item_width;
	/** 导航栏箭头 */
	// private ImageView rawImage;
	// /** 是否在移动，由于这边是动画结束后才进行的数据更替，设置这个限制为了避免操作太频繁造成的数据错乱。 */
	// private Animation animEnter = null;
	// private Animation animExit = null;
	// private Animation animShow = null;
	// private Animation animDissmiss = null;
	/** 导航栏动画相关参数 */
	private int endPosition;
	private int beginPosition;
	private int currentFragmentIndex;
	private boolean isEnd;

	/** 主页加载的Fragment */
	private ArrayList<Fragment> fragments;

	String name = "";
	String id = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_collecter);
		mContext = CollecterActivity.this;
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		mScreenWidth = dm.widthPixels;
		mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv_view);
		mLinearLayout = (LinearLayout) findViewById(R.id.hsv_content);
		mImageView = (ImageView) findViewById(R.id.img1);
		item_width = (int) ((mScreenWidth / 4.0));
		mImageView.getLayoutParams().width = item_width + 7;
		pager = (ViewPager) findViewById(R.id.pager);
		// 记得释放开Name
		name = getIntent().getExtras().getString("name");
		mTittle = (TextView) findViewById(R.id.tittle_text);
		if (TextUtils.isEmpty(name)) {
			mTittle.setText("艺术家");
		} else {
			mTittle.setText(name);
		}

		mBack = (ImageView) findViewById(R.id.back_btn);
		mBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		ImageView moreBtn = (ImageView) findViewById(R.id.tittle_search);
		moreBtn.setImageResource(R.drawable.jg_xq_share);
		moreBtn.setVisibility(View.VISIBLE);
		moreBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//分享
				AppUtil.showShare(mContext,CollecterIntroActivity.artistName,"艺术家分享",CollecterIntroActivity.artistImg,CollecterIntroActivity.artisUrl);
			}
		});
		// 记得释放开ID
		id = getIntent().getExtras().getString("id");
		initNav();
		initViewPager();
		// mShelter = (RelativeLayout) findViewById(R.id.ll_shelter);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	private void initViewPager() {
		fragments = new ArrayList<Fragment>();
		for (int i = 0; i < 4; i++) {
			Bundle data = new Bundle();
			data.putString("id", id);
			if (i == 0) {
				CollecterIntroActivity fragment = new CollecterIntroActivity();
				fragment.setArguments(data);
				fragments.add(fragment);
			}
			if (i == 1) {
				CollecterDynActivity fragment = new CollecterDynActivity();
				fragment.setArguments(data);
				fragments.add(fragment);
			}
            if (i==2) {
                CollecterOnsaleActivity fragment = new CollecterOnsaleActivity();
                fragment.setArguments(data);
                fragments.add(fragment);
            }

			if (i == 3) {
				CollecterNewsActivity fragment = new CollecterNewsActivity();
				fragment.setArguments(data);
				fragments.add(fragment);
			}
		}
		MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
				getSupportFragmentManager(), fragments);
		pager.setAdapter(fragmentPagerAdapter);
		fragmentPagerAdapter.setFragments(fragments);
		pager.setOnPageChangeListener(new MyOnPageChangeListener());
		pager.setCurrentItem(0);
	}

	private void initNav() {
        String[] arrTag = {"简介","动态","在售","资讯"};
        mLinearLayout.removeAllViews();
        for (int i = 0; i < 4; i++) {
            RelativeLayout layout = new RelativeLayout(this);
            TextView view = new TextView(this);
            view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            view.setText(arrTag[i]);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            layout.addView(view, params);
            mLinearLayout.addView(layout, item_width, VeDate.dip2px(mContext, 40));
            layout.setOnClickListener(this);
            layout.setTag(i);
        }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
		private ArrayList<Fragment> fragments;
		private FragmentManager fm;

		public MyFragmentPagerAdapter(FragmentManager fm) {
			super(fm);
			this.fm = fm;
		}

		public MyFragmentPagerAdapter(FragmentManager fm,
				ArrayList<Fragment> fragments) {
			super(fm);
			this.fm = fm;
			this.fragments = fragments;
		}

		@Override
		public int getCount() {
			return fragments.size();
		}

		@Override
		public Fragment getItem(int position) {
			return fragments.get(position);
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		public void setFragments(ArrayList<Fragment> fragments) {
			if (this.fragments != null) {
				FragmentTransaction ft = fm.beginTransaction();
				for (Fragment f : this.fragments) {
					ft.remove(f);
				}
				ft.commit();
				ft = null;
				fm.executePendingTransactions();
			}
			this.fragments = fragments;
			notifyDataSetChanged();
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			Object obj = super.instantiateItem(container, position);
			return obj;
		}

	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(final int position) {
			Animation animation = new TranslateAnimation(endPosition, position
					* item_width, 0, 0);

			beginPosition = position * item_width;

			currentFragmentIndex = position;
			if (animation != null) {
				animation.setFillAfter(true);
				animation.setDuration(0);
				mImageView.startAnimation(animation);
				mHorizontalScrollView.smoothScrollTo((currentFragmentIndex - 1)
						* item_width, 0);
			}
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
			if (!isEnd) {
				if (currentFragmentIndex == position) {
					endPosition = item_width * currentFragmentIndex
							+ (int) (item_width * positionOffset);
				}
				if (currentFragmentIndex == position + 1) {
					endPosition = item_width * currentFragmentIndex
							- (int) (item_width * (1 - positionOffset));
				}

				Animation mAnimation = new TranslateAnimation(beginPosition,
						endPosition, 0, 0);
				mAnimation.setFillAfter(true);
				mAnimation.setDuration(0);
				mImageView.startAnimation(mAnimation);
				mHorizontalScrollView.invalidate();
				beginPosition = endPosition;
			}
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_DRAGGING) {
				isEnd = false;
			} else if (state == ViewPager.SCROLL_STATE_SETTLING) {
				isEnd = true;
				beginPosition = currentFragmentIndex * item_width;
				if (pager.getCurrentItem() == currentFragmentIndex) {
					// 未跳入下一个页面
					mImageView.clearAnimation();
					Animation animation = null;
					// 恢复位置
					animation = new TranslateAnimation(endPosition,
							currentFragmentIndex * item_width, 0, 0);
					animation.setFillAfter(true);
					animation.setDuration(1);
					mImageView.startAnimation(animation);
					mHorizontalScrollView.invalidate();
					endPosition = currentFragmentIndex * item_width;
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		pager.setCurrentItem((Integer) v.getTag());
	}

	/**
	 * 获取点击的Item的对应View，
	 * 
	 * @param view
	 * @return
	 */
	private ImageView getView(View view) {
		view.destroyDrawingCache();
		view.setDrawingCacheEnabled(true);
		Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
		view.setDrawingCacheEnabled(false);
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(cache);
		return iv;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}
}
